<?php

class lang implements ArrayAccess, Iterator {
	
	private $localizationArray=array();
	private $validOffset = false;
	public static $lang='en';
	public static $page='home';
	
	function __construct($localeArray) {
		$this->localizationArray=$localeArray;
	}
	
	public static function get($file, $lang) {
		require_once('locale/'.$lang.'/'.$file.'.php');
		return new self(self::getLocale($file));
	}
	
	public static function getLocale($pageName) {
		switch($pageName) {
			case 'default' : 
				return i18n_default::getLocalizationArray();
				break;
			case 'common' :
				return i18n_common::getLocalizationArray();
				break;
			case 'error' :
				return i18n_error::getLocalizationArray();
				break;
			default :
				Throw new Exception('Page name unknonwn ['.$pageName.']');
				break;
		}
	}
	
	public function msg() {
		$args=func_get_args();
		$i = $args[0];
		if (!isset($this->localizationArray[$i])) return "";
		if (func_num_args()>1) {
			$args[0] = $this->localizationArray[$i];
			return call_user_func_array('sprintf', $args);
		}
        return $this->localizationArray[$i];
		//return $this->localizationArray[$str];
	}
	
	public function __get($varName){
		$args=func_get_args();
		$i = $args[0];
		if (!isset($this->localizationArray[$i])) return "";
		if (func_num_args()>1) {
			$args[0] = $this->localizationArray[$i];
			return call_user_func_array('sprintf', $args);
		}
        return $this->localizationArray[$i];
		//return isset($this->localizationArray[$varName]) ? $this->localizationArray[$varName] : null;
	}
	
	/** Methods for interface ArrayAccess
	 * http://www.php.net/manual/fr/class.arrayaccess.php
	 *  */
	
	public function offsetExists($offset){
		return isset($this->localizationArray[$offset]);
	}
	
	public function offsetGet($offset){
		return $this->__get($offset);
	}
	
	public function offsetSet($offset, $value){
		throw new Exception("Only read translation");
	}
	
	public function offsetUnset($offset){
		throw new Exception("Only read translation");
	}
	/** End of methods for interface ArrayAccess */
	
	/** Methods for interface Iterator
	 * http://www.php.net/manual/fr/class.iterator.php
	 *  */
	
	public function current(){
		return current($this->localizationArray);
	}
	
	public function key(){
		return key($this->localizationArray);
	}
	
	public function next(){
		$this->validOffset = next($this->localizationArray) != false ? true : false;
		}
	
	public function rewind(){
		$this->validOffset = true;
		reset($this->localizationArray);
	}
	
	public function valid(){
		return $this->validOffset;
	}
	
	
	
}